<?php //ver.2009 2.4 - Eugenio Ghiglia <eugenio@blux.org> -

       ////////////////////////////////
/////// manipolazione indirizzi email ///////
       ///////////////////////////////

 function ismail($indirizzo) {
   if(eregi("^[a-zA-Z0-9]+[_a-zA-Z0-9-]*(\.[_a-z0-9-]+)*@[a-z0-9]+(-[a-z0-9]+)*(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $indirizzo))
      return true;
   else
      return false;
 }

       ///////////////////////////
/////// manipolazione delle date ////////////
       //////////////////////////

    //////
    // conversione di una data YYYY-MM-DD in DD-MM-YYYY
    //
function amg2gma($data, $sep="-") {
    $returned = false;
    $data=trim($data);
    if ($data) {
        list($a, $m, $g) = explode($sep, $data);
        $returned = $g.$sep.$m.$sep.$a;
    }
    return $returned;
}

       //////////////////////////
/////// manipolazione delle ore /////////////
       /////////////////////////

    //////
    // tronca i secondi nel formato HH:MM:SS -> HH:MM
    //
function hms2hm($ora, $sep=":") {
    $returned = false;
    $ora=trim($ora);
    if ($ora) {
        list($h, $m, $s) = explode($sep, $ora);
        $returned = $h.$sep.$m;
    }
    return $returned;
}

      ///////////////////////////
////// manipolazione codice HTML ////////////
      ///////////////////////////
      
    //////
    // tronca un codice html in base al numero di parole
    // da visualizzare e rimuove i tag html
    //
function html_truncw($codice, $nparole="50") {
    $returned = false;
    $parole = Array();
    $codice = strip_tags($codice);
    $parole = explode(" ", $codice);
    if ($nparole>0) $returned = "";
    for ($i=0; $i<$nparole; $i++) {
        $returned .= $parole[$i] . " ";
    }
    if ($i) $retuned = trim($retuned);
    return $returned;
}


      /////////////////////////
////// manipolazione immagini ////////////
      ////////////////////////

    ////////////////////////////////////////////////////////////////////
    ///
    /// Ridimensionamento di una immagine (il file viene sovrascritto)
    ///    
    function ridimensiona_immagine($immagine, $resize_width, $resize_height) {
    $returned=true;

    if (!file_exists($immagine)) return false;

    $file_lowcase=strtolower($immagine);
    $ext=explode(".",$file_lowcase);
    $n_ext=count($ext)-1;
                        
    if ( stristr("jpg jpeg gif png bmp", $ext[$n_ext]) ) {
            
         list($width, $height, $type, $attr)=getimagesize($immagine);
         
         
         //// ridimensionamento proporzionale ////
            
            if ($resize_width=="*" && $resize_height=="*") {
                $resize_width=$width;
                $resize_height=$height;
            }
            
         
            if ($resize_width=="*")
                $resize_width=ceil(($width/$height)*$resize_height); 
            else
                if (!is_numeric($resize_width)) $resize_width=$width;
            
            
            if ($resize_height=="*") 
                $resize_height=ceil(($height/$width)*$resize_width);
            else
                if (!is_numeric($resize_height)) $resize_height=$height;
         
         /////////////////////////////////////////
         
            
         $thumb = imagecreatetruecolor($resize_width, $resize_height);
         
         switch($ext[$n_ext]) {
            
            case "jpg":
            case "jpeg":
                $source = imagecreatefromjpeg($immagine);
            break;
                
            case "gif":
                $source = imagecreatefromgif($immagine);
            break;
            
            case "png";
                $source = imagecreatefrompng($immagine);
            break;
            
            case "bmp":
                $source = imagecreatefromwbmp($immagine);
            break;
            
            default:
                return false;
            break;
         }
         
         
         imagecopyresampled($thumb, $source, 0, 0, 0, 0, $resize_width, $resize_height, $width, $height);
           
        
        // qui sovrascrive il file immagine
        switch($ext[$n_ext]) {
        
            case "jpg":
            case "jpeg":
                
                imagejpeg($thumb, $immagine);
            break;
                
            case "gif":
                
                imagegif($thumb, $immagine);
            break;
            
            case "png";
                
                imagepng($thumb, $immagine);
            break;
            
            case "bmp":
                
                imagewbmp($thumb, $immagine);
            break;
            
            default:
                $returned = false;
            break;
         }
    }

    return $returned;
}


    function cropImage($nw, $nh, $immagine) {
     
        $size = getimagesize($immagine);
        $w = $size[0];
        $h = $size[1];
     
        if (!file_exists($immagine)) return false;

        $file_lowcase=strtolower($immagine);
        $ext=explode(".",$file_lowcase);
        $n_ext=count($ext)-1;
                        
        if ( stristr("jpg jpeg gif png bmp", $ext[$n_ext]) ) {
     
                 switch($ext[$n_ext]) {
            
                    case "jpg":
                    case "jpeg":
                        $source = imagecreatefromjpeg($immagine);
                    break;
                        
                    case "gif":
                        $source = imagecreatefromgif($immagine);
                    break;
                    
                    case "png";
                        $source = imagecreatefrompng($immagine);
                    break;
                    
                    case "bmp":
                        $source = imagecreatefromwbmp($immagine);
                    break;
                    
                    default:
                        return false;
                    break;
                 }
             
                $dimg = imagecreatetruecolor($nw, $nh);
             
                $wm = $w/$nw;
                $hm = $h/$nh;
             
                $h_height = $nh/2;
                $w_height = $nw/2;
             
                if($w> $h) {
             
                    $adjusted_width = $w / $hm;
                    $half_width = $adjusted_width / 2;
                    $int_width = $half_width - $w_height;
             
                    imagecopyresampled($dimg,$source,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
             
                } elseif(($w <$h) || ($w == $h)) {
             
                    $adjusted_height = $h / $wm;
                    $half_height = $adjusted_height / 2;
                    $int_height = $half_height - $h_height;
             
                    imagecopyresampled($dimg,$source,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
             
                } else {
                    imagecopyresampled($dimg,$source,0,0,0,0,$nw,$nh,$w,$h);
                }
            
                switch($ext[$n_ext]) {
        
                    case "jpg":
                    case "jpeg":
                        
                        imagejpeg($dimg, $immagine, 100);
                    break;
                        
                    case "gif":
                        
                        imagegif($dimg, $immagine);
                    break;
                    
                    case "png";
                        
                        imagepng($dimg, $immagine);
                    break;
                    
                    case "bmp":
                        
                        imagewbmp($dimg, $immagine);
                    break;
                    
                    default:
                        $returned = false;
                    break;
                 }
    
        }
    }


      /////////////////////////
////// manipolazione stringhe ////////////
      ////////////////////////


//////////////////////////////////////////
// elimina dalla stringa tutti i caratteri 
// che non sono alfanumerici
//
function strtoalfanum($stringa) {
    $len=strlen($stringa);
    $strtmp="";
    for ($i=0;$i<$len;$i++) {
        $chr=$stringa[$i];
        if (eregi("^[a-zA-Z0-9]{1}$", $chr)) $strtmp.=$chr;
    }
    $stringa=$strtmp;     
    return $stringa;
}
//
///////////////////////////////////////////


///////////////////////////////////////////
// controlla se una stringa è alfanumerica
function check_alfanum($stringa, $extrachar) {
    $valida=true;
    $len=strlen($stringa);
    $i=0;
    while($i<$len && $valida) {
        $chr=$stringa[$i];
        if (!eregi("^[a-zA-Z0-9]{1}$", $chr) && !strstr($extrachar, $chr)) $valida=false;
        $i++;
    }
    
    return $valida;
}
//
///////////////////////////////////////////

//////////////////////////////////////////////////
// Select gg mm aa
function get_select_data($gg=0, $mm=0, $aa=0, $pre="", $anno="", $anni=5) {
    $buffer="<select name='".$pre."gg'>";
        for ($i=1;$i<32;$i++) {
                $d="00".$i;
                $d=substr($d, strlen($d)-2,2);
                $buffer.="<option value='$d' ".(($gg==$d)?"selected":"").">$d</option>";
                }
    $buffer.="</select>";
    $buffer.="<select name='".$pre."mm'>";
        for ($i=1;$i<13;$i++) {
                $d="00".$i;
                $d=substr($d, strlen($d)-2,2);
                $buffer.="<option value='$d' ".(($mm==$d)?"selected":"").">$d</option>";
                }
    $buffer.="</select>";
    $buffer.="<select name='".$pre."aa'>";
        if (!$aa) $aa=date("Y");
        if (!$anno) $anno=date("Y");
        if ($anni>0) {
            for ($i=$anno;$i<($anno+$anni);$i++) $buffer.="<option value='$i' ".(($aa==$i)?"selected":"").">$i</option>";
        } else {
            for ($i=$anno;$i>($anno+$anni);$i--) $buffer.="<option value='$i' ".(($aa==$i)?"selected":"").">$i</option>";
        }
    $buffer.="</select>";
    return $buffer;
}
//
///////////////////////////////////////////////////


////// 22/09/2008 /////////////////////////////////
// estrae i parametri passati in GET dall'URI
function uri2params($uri) {
    $tmp1=explode("?",$uri);
    $tmp2=explode("&",$tmp1[1]);
    $p=Array();
    foreach ($tmp2 as $v2) {
        $tmp3=explode("=",$v2);
        $p[$tmp3[0]]=$tmp3[1];
    }
    return $p;
}
//
///////////////////////////////////////////////////


///////////////////////////////////////////////////
// XML to ARRAY
function xml2array($url, $get_attributes = 1, $priority = 'tag')
{
    $contents = "";
    if (!function_exists('xml_parser_create'))
    {
        return array ();
    }
    $parser = xml_parser_create('');
    if (!($fp = @ fopen($url, 'rb')))
    {
        return array ();
    }
    while (!feof($fp))
    {
        $contents .= fread($fp, 8192);
    }
    fclose($fp);
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, trim($contents), $xml_values);
    xml_parser_free($parser);
    if (!$xml_values)
        return; //Hmm...
    $xml_array = array ();
    $parents = array ();
    $opened_tags = array ();
    $arr = array ();
    $current = & $xml_array;
    $repeated_tag_index = array ();
    foreach ($xml_values as $data)
    {
        unset ($attributes, $value);
        extract($data);
        $result = array ();
        $attributes_data = array ();
        if (isset ($value))
        {
            if ($priority == 'tag')
                $result = $value;
            else
                $result['value'] = $value;
        }
        if (isset ($attributes) and $get_attributes)
        {
            foreach ($attributes as $attr => $val)
            {
                if ($priority == 'tag')
                    $attributes_data[$attr] = $val;
                else
                    $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
            }
        }
        if ($type == "open")
        {
            $parent[$level -1] = & $current;
            if (!is_array($current) or (!in_array($tag, array_keys($current))))
            {
                $current[$tag] = $result;
                if ($attributes_data)
                    $current[$tag . '_attr'] = $attributes_data;
                $repeated_tag_index[$tag . '_' . $level] = 1;
                $current = & $current[$tag];
            }
            else
            {
                if (isset ($current[$tag][0]))
                {
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    $repeated_tag_index[$tag . '_' . $level]++;
                }
                else
                {
                    $current[$tag] = array (
                        $current[$tag],
                        $result
                    );
                    $repeated_tag_index[$tag . '_' . $level] = 2;
                    if (isset ($current[$tag . '_attr']))
                    {
                        $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                        unset ($current[$tag . '_attr']);
                    }
                }
                $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
                $current = & $current[$tag][$last_item_index];
            }
        }
        elseif ($type == "complete")
        {
            if (!isset ($current[$tag]))
            {
                $current[$tag] = $result;
                $repeated_tag_index[$tag . '_' . $level] = 1;
                if ($priority == 'tag' and $attributes_data)
                    $current[$tag . '_attr'] = $attributes_data;
            }
            else
            {
                if (isset ($current[$tag][0]) and is_array($current[$tag]))
                {
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    if ($priority == 'tag' and $get_attributes and $attributes_data)
                    {
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                    }
                    $repeated_tag_index[$tag . '_' . $level]++;
                }
                else
                {
                    $current[$tag] = array (
                        $current[$tag],
                        $result
                    );
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    if ($priority == 'tag' and $get_attributes)
                    {
                        if (isset ($current[$tag . '_attr']))
                        {
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                            unset ($current[$tag . '_attr']);
                        }
                        if ($attributes_data)
                        {
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                        }
                    }
                    $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
                }
            }
        }
        elseif ($type == 'close')
        {
            $current = & $parent[$level -1];
        }
    }
    return ($xml_array);
}
//
///////////////////////////////////////////////////


////////////////////////////////////////////////////
//
function get_dominio() {
    $tmp=explode(".",$_SERVER["SERVER_NAME"]);
    $c=count($tmp); $b=""; $s="";
    for ($i=1;$i<$c;$i++) {$b.=$s.$tmp[$i]; $s=".";}
    return $b;
}
//
////////////////////////////////////////////////////


////////////////////////////////////////////////////
//
function getJPEGImageXY($data) {
    $soi = unpack('nmagic/nmarker', $data);
    if ($soi['magic'] != 0xFFD8) return false;
    $marker = $soi['marker'];
    $data   = substr($data, 4);
    $done   = false;
    while(1) {
            if (strlen($data) === 0) return false;
            switch($marker) {
                    case 0xFFC0:
                            $info = unpack('nlength/Cprecision/nY/nX', $data);
                            return array($info['X'], $info['Y']);
                            break;

                    default:
                            $info   = unpack('nlength', $data);
                            $data   = substr($data, $info['length']);
                            $info   = unpack('nmarker', $data);
                            $marker = $info['marker'];
                            $data   = substr($data, 2);
                            break;
            }
    }
}
//
////////////////////////////////////////////////////   


////////////////////////////////////////////////////
// *** funzione invio mail con classe phpmailer ***
function mailto($mailto,$subject,$message,$from,$cc='',$attach_b64='',$attach_name='') {
    global $db;
    global $_SESSION;
    require_once('class.phpmailer.php');
    
    $mail = new phpmailer;
    $mail->IsMail(); 
    $mail->Encoding='8bit';
    $mail->From = $from;
    $mail->FromName = $from;
    // mailto
    $mail->AddAddress($mailto);
    // CC
    if ($cc) $mail->AddCC($cc);
    // allegato
    if ($attach_name) $mail->AddStringAttachment(base64_decode($attach_b64), $attach_name); 
    
    $mail->IsHTML(false);
    $mail->WordWrap = 82;
    //$mail->Subject = utf8_decode($subject);
    //$mail->Body = utf8_decode($message);
    $mail->Subject = $subject;
    $mail->Body = $message;
    return $mail->Send();
}
//
////////////////////////////////////////////////////

function genera_password($num_char=6) {
    $psw='';
    $str[0]='1';
    $str[1]='2';
    $str[2]='3';
    $str[3]='4';
    $str[4]='5';
    $str[5]='6';
    $str[6]='7';
    $str[7]='8';
    $str[8]='9';
    $str[9]='a';
    $str[10]='b';
    $str[11]='c';
    $str[12]='d';
    $str[13]='e';
    $str[14]='f';
    $str[15]='g';
    $str[16]='h';
    $str[17]='m';
    $str[18]='n';
    $str[19]='p';
    $str[20]='r';
    $str[21]='s';
    $str[22]='u';
    $str[23]='v';
    $str[24]='z';
    $str[25]='k';
    $str[26]='x';
    $str[27]='w';
    $str[28]='@';
    $str[29]='.';
    $str[30]='?';
    $str[31]='/';
    $str[32]='%';
    $str[33]='!';
    $str[34]='&';
    $str[35]='#';
    
    for ($i=0;$i<$num_char;$i++) {
        $psw.=$str[rand(0,35)];
    }
    
    return $psw;
}

function stringtourl($stringa) {
    $stringa=trim(strtolower($stringa));
    $stringa=str_replace(' ','-',$stringa);
    $stringa=str_replace('_','-',$stringa);
    $stringa=str_replace('\'','-',$stringa);
    $stringa=str_replace('è','e',$stringa);
    $stringa=str_replace('é','e',$stringa);
    $stringa=str_replace('à','a',$stringa);
    $stringa=str_replace('ì','i',$stringa);
    $stringa=str_replace('ò','o',$stringa);
    $stringa=str_replace('u','u',$stringa);
    $len=strlen($stringa);
    $strtmp="";
    for ($i=0;$i<$len;$i++) {
        $chr=$stringa[$i];
        if (eregi("^[a-zA-Z0-9\-]{1}$", $chr)) $strtmp.=$chr;
    }
    $stringa=$strtmp;
    $stringa=str_replace('--','-',$stringa);
    $stringa=str_replace('--','-',$stringa);
    return $stringa;
}

function convertilink($testo) {
    $m=preg_match_all('/http:\/\/[a-z0-9A-Z.]+(?(?=[\/])(.*))/',$testo,$match);
    //print_r($match);
    
    if ($m) {  
        $links=$match[0];
        for ($j=0;$j<$m;$j++) {
            $testo=str_replace($links[$j],'<a href="'.$links[$j].'" rel="external nofollow" target="_blank">'.$links[$j].'</a>',$testo);
        }
    }
    return $testo;
}

function antispam() {
    $buffer='';
    $arr[0][0]='zero';
    $arr[0][1]='uno';
    $arr[0][2]='due';
    $arr[0][3]='tre';
    $arr[0][4]='quattro';
    $arr[0][5]='cinque';
    $arr[0][6]='sei';
    $arr[0][7]='sette';
    $arr[0][8]='otto';
    $arr[0][9]='nove';
    $arr[0][10]='dieci';
    $arr[1][0]='0';
    $arr[1][1]='1';
    $arr[1][2]='2';
    $arr[1][3]='3';
    $arr[1][4]='4';
    $arr[1][5]='5';
    $arr[1][6]='6';
    $arr[1][7]='7';
    $arr[1][8]='8';
    $arr[1][9]='9';
    $arr[1][10]='10';
    
    if (rand(0,1)) {
     $a=rand(0,10);
     $b=rand(0,10);
     $_SESSION['antispam']=$a+$b;
     $buffer=$arr[rand(0,1)][$a].' '.((rand(0,1))?'pi&ugrave;':'+').' '.$arr[rand(0,1)][$b];   
    } else {
     $a=rand(0,10);
     $b=rand(0,10);
     $_SESSION['antispam']=$a-$b;
     $buffer=$arr[rand(0,1)][$a].' '.((rand(0,1))?'meno':'-').' '.$arr[rand(0,1)][$b];   
    }
    
    return $buffer;
} 
    
    
?>